package cn.lyl.basic.controller;

import cn.lyl.basic.util.AjaxResult;
import cn.lyl.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传   Post
 * 下载 = 不需要
 * 删除   Delete
 * 更新 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename(); //获取原始文件名
            String extname = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String filename = FastDfsUtils.upload(file.getBytes(), extname);
            //将上传之后的名字响应给前端
            return AjaxResult.me().setResultObj(filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败！");
        }
    }

    /**
     *删除接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam("path") String path){
        try {
            String pathTem = path.substring(1);
            String group = pathTem.substring(0, pathTem.indexOf("/"));
            String filePath = pathTem.substring(pathTem.indexOf("/") + 1);
            FastDfsUtils.delete(group,filePath);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
